import datetime
import re

import serial
from cfg.base.cmd import cmd_set
from cfg.base.init_cmd import only_once
from common.gene_log import write_log
from cfg.base.timeout_cmd import timeout_5, timeout_10


class My_Serial():

    def __init__(self, port):
        self.port = port
        self.baud_rate = 115200
        self.timeout = 1

    def Gene_Serial(self):

        ser = serial.Serial(port=self.port, baudrate=self.baud_rate, timeout=self.timeout)
        return ser

    def Send_AT(self):
        ser = self.Gene_Serial()
        self.ser = ser
        if ser.is_open:
            print("自动化程序已启动！！！")
            x = 0
            while True:
                for j in range(0, cmd_set.__len__()):
                    for i in range(0, cmd_set[j].__len__()):
                        cmd = cmd_set[j][i][0]
                        at_cmd = cmd_set[j][i][1]
                        match_result = cmd_set[j][i][2]
                        x += 1

                        while not cmd:
                            if at_cmd in timeout_5:
                                ser.timeout = 5
                            elif at_cmd in timeout_10:
                                ser.timeout = 10
                            else:
                                ser.timeout = 1
                            at_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            print("正在执行第%s条AT命令" % x)
                            s = ser.write((at_cmd + "\r\n").encode())
                            if at_cmd in only_once:
                                cmd_set[j][i][0] = 1
                            req_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            result = ser.read(300).decode().replace("\r\n", "\r")
                            write_log(at_cmd, result, at_time, req_time, log_name=".log")
                            try:
                                if re.search(match_result, result):
                                    print(at_cmd + ": test ok")
                                else:
                                    write_log(at_cmd, result, at_time, req_time, log_name=".logerr")
                                    print(at_cmd + ": test fail")
                                break
                            except Exception as e:
                                print(e)
                                e = str(e)
                                e = e + "\r\n"
                                write_log(at_cmd, result, at_time, req_time, log_name=".Exception")
                                break
        else:
            print("端口打开失败！！！")


    def run(self):
        self.Send_AT()
